﻿using System;
using System.Collections.Generic;
using Sinacor.Infra.UI.Common;
using Sinacor.UI.Application.Menu.Model;
using PSE.Framework.ErrorLogging;
using Sinacor.Infra.UI.Exceptions;
using Sinacor.Infra.Common.Exceptions;

namespace Sinacor.UI.Application.Menu.Presenter
{
    public class MenuPresenter : BasePresenter<IMenu>
    {
        Communication.Menu _communication;

        public MenuPresenter(IMenu view)
            : base(view)
        {
        }

        public List<Company> RetrieveCompanies()
        {
            List<Company> companies = new List<Company>();
            try
            {
                _communication = new Communication.Menu(this.Session);
                companies = _communication.RetrieveCompanies();
                _communication = null;
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }

            return companies;
        }

        public List<Module> RetrieveModules(int companyId)
        {
            return this.RetrieveModules(companyId, true);
        }

        public List<Module> RetrieveModules(int companyId, bool throwException)
        {
            List<Module> modules = new List<Module>();
            try
            {
                _communication = new Communication.Menu(this.Session);
                modules = _communication.RetrieveModules(companyId);
                _communication = null;
            }
            catch (Exception ex)
            {
                if (throwException)
                {
                    HandleException(ex);
                }
                else
                {
                    ErrorMessage.ConfigureExceptionMessage(ex);

                    Dictionary<string, object> extensionData = null;

                    if (ex is BaseLogException &&
                        ((BaseLogException)ex).SourceAddress != null &&
                        !string.IsNullOrEmpty(((BaseLogException)ex).LogData))
                    {
                        extensionData = new Dictionary<string, object>() { { "InnerLogData", ((BaseLogException)ex).LogData } };
                    }

                    Sinacor.Infra.UI.ErrorLogging.ErrorLogger.WriteLog(LogType.Warning, ex, extensionData);
                }
            }

            return modules;
        }

        public bool CheckRolePermission(string role, string moduleId, int companyId)
        {
            bool retorno = false;
            try
            {
                _communication = new Communication.Menu(this.Session);
                retorno = _communication.CheckRolePermission(role, moduleId, companyId);
                _communication = null;
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }

            return retorno;
        }
    }
}